################################################################################
# Build stage 1 `builder`:
# Download and extract RocketMQ
################################################################################
From arm64v8/maven:3.8.6-openjdk-8-slim AS builder

ENV VERSION=5.1.3

COPY sources.list    /etc/apt/sources.list

RUN set -eux; \
    apt-get update; \
    DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
        gnupg2 \
        unzip \
    ; \
    rm -rf /var/lib/apt/lists/*

RUN curl -L https://archive.apache.org/dist/rocketmq/${VERSION}/rocketmq-all-${VERSION}-bin-release.zip -o rocketmq.zip \
    && curl -L https://archive.apache.org/dist/rocketmq/${VERSION}/rocketmq-all-${VERSION}-bin-release.zip.asc -o rocketmq.zip.asc \
        && curl -L https://www.apache.org/dist/rocketmq/KEYS -o KEYS \
    && gpg --import KEYS \
    && gpg --batch --verify rocketmq.zip.asc rocketmq.zip

RUN unzip rocketmq.zip \
    && mkdir -p /tmp/rocketmq-${VERSION} \
        && mv rocketmq*/* /tmp/rocketmq-${VERSION}

################################################################################
# Build stage 2:
# Make the actual RocketMQ docker image
################################################################################
FROM arm64v8/maven:3.8.6-openjdk-8-slim

ARG user=rocketmq
ARG group=rocketmq
ARG uid=3000
ARG gid=3000

# Rocketmq version
ENV ROCKETMQ_VERSION=5.1.3

# Rocketmq home
ENV ROCKETMQ_HOME=/home/rocketmq/rocketmq-${ROCKETMQ_VERSION}

# expose namesrv port
EXPOSE 9876
EXPOSE 9877 9878
# expose broker ports
EXPOSE 10909 10911 10912

# RocketMQ is run with user `rocketmq`, uid = 3000
# If you bind mount a volume from the host or a data container,
# ensure you use the same uid
COPY sources.list    /etc/apt/sources.list
RUN groupadd -g ${gid} ${group} \
    && useradd -l -u ${uid} -g ${gid} -m -s /bin/bash ${user} \
    && apt-get update; \
    DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
        less \
        openssl \
        which \
    \
    && apt-get clean; \
    rm -rf /var/lib/apt/lists/*

# Copy customized scripts
COPY scripts/ ${ROCKETMQ_HOME}/bin/

# Copy RocketMQ artifact from builder
COPY --from=builder --chown=${uid}:${gid} /tmp/rocketmq-${ROCKETMQ_VERSION}/ ${ROCKETMQ_HOME}

# Override customized scripts for namesrv
# Override customized scripts for broker
# Export Java options

# Add ${JAVA_HOME}/lib/ext as java.ext.dirs
RUN chmod -R a+x ${ROCKETMQ_HOME}/bin/ \
 && export JAVA_OPT=" -Duser.home=/opt" \
 && sed -i 's/${JAVA_HOME}\/jre\/lib\/ext/${JAVA_HOME}\/jre\/lib\/ext:${JAVA_HOME}\/lib\/ext/' ${ROCKETMQ_HOME}/bin/tools.sh \
 && chown -R ${uid}:${gid} ${ROCKETMQ_HOME}


WORKDIR ${ROCKETMQ_HOME}/bin

# ENTRYPOINT ["./docker-entrypoint.sh"]
# Dummy overridable parameter parsed by entrypoint
# CMD ["dummy"]